//
//  ApplyViewController.m
//  dangdang
//
//  Created by air on 15/12/17.
//  Copyright © 2015年 luweijie. All rights reserved.
//

#import "ApplyViewController.h"
#import "IdentificationCardViewController.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

@interface ApplyViewController ()

@property (nonatomic, strong) CityPickerView *pick;
@property (nonatomic, copy) NSString * provice;
@property (nonatomic, copy) NSString * city;
@property (nonatomic, copy) NSString * county;

@end

@implementation ApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    for (UITextField * textField in _textFieldArray) {
        textField.delegate = self;
        if (textField.tag == 1 || textField.tag == 3) {
            textField.keyboardType = UIKeyboardTypeNumberPad;
        }
    }
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:singleTap];
    
    _messageTextView.userInteractionEnabled = NO;
    _backView.hidden = YES;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(nextStep)];
    
    self.title = @"申请为速送员";
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer

{
    [self.view endEditing:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)pushPicker:(UIButton *)sender {
    _backView.hidden = NO;
    self.pick = [[CityPickerView alloc] initWithFrame:CGRectMake(0, 50, self.view.bounds.size.width, 200)];
    self.pick.delegate = self;
    [self.backView addSubview:self.pick];
}

- (IBAction)confirm:(UIButton *)sender {
    if (_provice == nil) {
        _areaLabel.text = [NSString stringWithFormat:@"%@ %@ %@", @"北京市", @"北京市", @"东城区"];
    }else{
        _areaLabel.text = [NSString stringWithFormat:@"%@ %@ %@", _provice, _city, _county];
    }
    _areaLabel.textColor = [UIColor blackColor];
    [_pick removeFromSuperview];
    _backView.hidden = YES;
}

- (void) updateLabel {
    _provice = [self.pick.proviceDictionary objectForKey:@"provice"];
    _city = [self.pick.proviceDictionary objectForKey:@"city"];
    _county = [self.pick.proviceDictionary objectForKey:@"county"];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 1) {
        return [self validateNumber:string];
    }
    return YES;
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (void)nextStep{
    if ([_areaLabel.text isEqualToString:@"请选择省市区"]) {
        [self alertViewShowWithAlertString:@"地区不能为空"];
        return;
    }
    if ([_nameTextField.text isEqual:nil] || [_nameTextField.text isEqualToString:@""]) {
        [self alertViewShowWithAlertString:@"姓名不能为空"];
        return;
    }
    if ([_certificateTextField.text isEqual:nil] || [_certificateTextField.text isEqualToString:@""]) {
        [self alertViewShowWithAlertString:@"身份证号不能为空"];
        return;
    }
    if (_certificateTextField.text.length == 15 || _certificateTextField.text.length == 18) {
        NSString *emailRegex = @"^[0-9]*$";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
        bool sfzNo = [emailTest evaluateWithObject:[_certificateTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
        
    if (_certificateTextField.text.length == 15) {
            if (!sfzNo) {
                [self alertViewShowWithAlertString:@"请输入正确的身份证号"];
                return;
            }
        }else if (_certificateTextField.text.length == 18) {
            bool sfz18NO = [self checkIdentityCardNo:_certificateTextField.text];
            if (!sfz18NO) {
                [self alertViewShowWithAlertString:@"请输入正确的身份证号"];
                return;
            }
        }
    }else{
        [self alertViewShowWithAlertString:@"请输入正确的身份证号"];
        return;
    }
    if ([_emergentTextField.text isEqual:nil] || [_emergentTextField.text isEqualToString:@""]) {
        [self alertViewShowWithAlertString:@"紧急联系人不能为空"];
        return;
    }
    if ([_phoneTextField.text isEqual:nil] || [_phoneTextField.text isEqualToString:@""]) {
        [self alertViewShowWithAlertString:@"手机号码不能为空"];
        return;
    }
    if ([self isMobileNumber:_phoneTextField.text] == NO) {
        [self alertViewShowWithAlertString:@"手机号码格式不正确"];
        return;
    }
    
    NSString * userID = userObject.userID;
    NSString * areaString = _areaLabel.text;
    NSString * nameString = _nameTextField.text;
    NSString * certificateString = _certificateTextField.text;
    NSString * emergentString = _emergentTextField.text;
    NSString * phoneString = _phoneTextField.text;
    NSString * token = userObject.accessToken;
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userID forKey:@"uid"];
    [params setObject:nameString forKey:@"uname"];
    [params setObject:areaString forKey:@"address"];
    [params setObject:certificateString forKey:@"cpersionid"];
    [params setObject:emergentString forKey:@"cemname"];
    [params setObject:phoneString forKey:@"cemphone"];
    
    [self postRequestWithMethodName:@"courier/request" andParams:params andSender:nil];
    [LoadingView showInView:self.view image:nil info:@"通讯中，请稍候..." animated:YES modeled:YES autoHide:NO];
}

#pragma mark - 身份证识别
- (BOOL)checkIdentityCardNo:(NSString*)cardNo
{
    if (cardNo.length != 18) {
        return  NO;
    }
    NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
    
    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
        return NO;
    }
    int sumValue = 0;
    
    for (int i =0; i<17; i++) {
        sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
    }
    
    NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]];
    
    if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
        return YES;
    }
    return  NO;
}

- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (IBAction)contactButton:(UIButton *)sender {
    dispatch_async(dispatch_get_main_queue(), ^
                   
                   {
                       CNContactPickerViewController * con = [[CNContactPickerViewController alloc] init];
                       [self presentViewController:con animated:YES completion:Nil];
                   });
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([code isEqualToString:@"0"]) {
            IdentificationCardViewController * identificationboardVC = [[UIStoryboard storyboardWithName:@"IdentificationCardViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"IdentificationCardViewController"];
            [self.navigationController pushViewController:identificationboardVC animated:YES];
        }else{
            [self alertViewShowWithAlertString:@"提交失败"];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
